/**
 * Created by 白雨浓 on 2018/4/12 16:30.
 *
 * axios
 */

import axios from 'axios';
import router from '../router';
import Vue from 'vue';

const self = Vue.prototype;

const toast = {
    suc(msg) {
        self.$message({message: msg, type: 'success'});
    },
    err(msg) {
        self.$message({message: msg, type: 'error'});
    },
};

const ajax = axios.create({
    baseURL: '/api',
    timeout: 10000,
    responseType: 'json',
    withCredentials: true, // 是否允许带cookies
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'User-From': 'cbdp-admin-web',
        'Authorization': '',//TODO: 2018年10月25日21:35:55
    },
});

/** 请求拦截器 */
ajax.interceptors.request.use(
    config => {
        return config;
    },
    err => Promise.reject(err),
);

const throwErrorMessage = data => {
    if (data.code) {
        if (data.code === -101) {
            router.push('/login');
        }
        if (data.code !== 0 && !!data.msg) {
            self.$message.error(data.msg);
        }
        return true;
    }
    return false;
};

/** 返回拦截器 */
ajax.interceptors.response.use(
    res => {
        const {data} = res;
        throwErrorMessage(data);
        return Promise.resolve(data);
    },
    err => {
        const res = err.response;

        switch (res.status) {
            case 404:
                toast.err('请求路径未找到');
                break;
            case 500: {
                if (res.data.code === -101) {
                    router.push('/login');
                } else {
                    toast.err(res.data.msg);
                }
            }
                break;
            default:
                toast.err(res.data && res.data.msg ? res.data.msg : err.message);
        }
        return Promise.reject(err);
    },
);

/** 请求封装 */
const fetch = (method, path, params, callback) => {
    if (typeof params === 'function') {
        callback = params;
        params = {};
    }

    if (['get', 'delete'].includes(method)) {
        return new Promise((resolve, reject) => {
            ajax[method](path, {params: params})
                .then(res => resolve(res))
                .catch(err => {
                    if (callback) {
                        callback();
                    }
                    reject(err);
                });
        });
    } else {
        return new Promise((resolve, reject) => {
            ajax[method](path, params)
                .then(res => resolve(res))
                .catch(err => {
                    if (callback) {
                        callback();
                    }
                    reject(err);
                });
        });
    }
};

/** 分类请求 */
export const get = (path, params, callback) => fetch('get', path, params, callback);
export const del = (path, params, callback) => fetch('delete', path, params, callback);
export const post = (path, params, callback) => fetch('post', path, params, callback);
export const put = (path, params, callback) => fetch('put', path, params, callback);
export const patch = (path, params, callback) => fetch('patch', path, params, callback);

export default {
    install(Vue) {
        Vue.prototype.$$axios = axios;
        Vue.prototype.$$ajax = ajax;
        Vue.prototype.$$get = get;
        Vue.prototype.$$delete = del;
        Vue.prototype.$$post = post;
        Vue.prototype.$$put = put;
        Vue.prototype.$$patch = patch;
    },
};
